package com.speed.vo;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Page;

public class VoPageHelper<T> {

	public Page<T> paginate(int pageNumber, int pageSize, List<T> vos) throws Exception {
		if (pageNumber < 1 || pageSize < 1)
			throw new ActiveRecordException("pageNumber and pageSize must be more than 0");

		int totalRow = vos.size();
		int totalPage = 0;

		totalPage = totalRow / pageSize;
		if (totalRow % pageSize != 0) {
			totalPage++;
		}

		return new Page<T>(pageResult(vos, pageNumber, pageSize), pageNumber, pageSize, totalPage, (int) totalRow);
	}

	private List<T> pageResult(List<T> ts, int pageNumber, int pageSize) {
		if (ts.size() <= pageSize) {
			return ts;
		}
		List<T> pageData = new ArrayList<T>();
		for (int i = (pageNumber - 1) * pageSize, j = 0; j < pageSize && i < ts.size(); j++, i++) {
			pageData.add(ts.get(i));
		}
		return pageData;
	}
}
